/**
 * Copyright 2019 吉鼎科技.
 *
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.utils;

import cn.easyplatform.lang.Strings;
import com.alibaba.fastjson.JSON;
import io.keikai.api.Exporter;
import io.keikai.api.Exporters;
import io.keikai.api.Importer;
import io.keikai.api.Importers;
import io.keikai.api.model.Book;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.util.media.AMedia;
import org.zkoss.zk.ui.Page;
import org.zkoss.zkex.zul.Pdfviewer;
import org.zkoss.zkmax.zul.Video;
import org.zkoss.zul.Audio;
import org.zkoss.zul.Image;
import org.zkoss.zul.Window;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class FileUtil {

    private final static Logger log = LoggerFactory.getLogger(FileUtil.class);

    private static BitSet dontNeedEncoding;

    static {
        dontNeedEncoding = new BitSet(256);
        int i;
        for (i = 'a'; i <= 'z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = 'A'; i <= 'Z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = '0'; i <= '9'; i++) {
            dontNeedEncoding.set(i);
        }
        dontNeedEncoding.set('+');
        dontNeedEncoding.set('-');
        dontNeedEncoding.set('_');
        dontNeedEncoding.set('.');
        dontNeedEncoding.set('*');
    }

    public static boolean hasUrlEncoded(String str) {
        boolean needEncode = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (dontNeedEncoding.get((int) c)) {
                continue;
            }
            if (c == '%' && (i + 2) < str.length()) {
                // 判断是否符合urlEncode规范
                char c1 = str.charAt(++i);
                char c2 = str.charAt(++i);
                if (isDigit16Char(c1) && isDigit16Char(c2)) {
                    continue;
                }
            }
            // 其他字符，肯定需要urlEncode
            needEncode = true;
            break;
        }

        return !needEncode;
    }

    private static boolean isDigit16Char(char c) {
        return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
    }

    /**
     * 预览图片等其它文档
     *
     * @param page
     * @param file
     */
    public static void preview(Page page, String file) {
        try {
            if (hasUrlEncoded(file))
                file = URLDecoder.decode(file, "utf-8");
            else {
                if (file.startsWith("/servlets/download?id=")) {
                    file = StringUtils.substringAfter(file, "/servlets/download?id=");
                    if (hasUrlEncoded(file))
                        file = URLDecoder.decode(file, "utf-8");
                }
            }
            String name = FilenameUtils.getName(file);
            Window win = new Window();
            win.setTitle(name);
            win.setClosable(true);
            win.setMaximizable(true);
            win.setHeight("450px");
            win.setWidth("600px");
            win.setMaximizable(true);
            win.setMaximized(true);
            String ext = FilenameUtils.getExtension(name);
            if (ext.startsWith("doc") || ext.startsWith("xls") || ext.startsWith("ppt") || ext.startsWith("pdf")) {
                Pdfviewer pdfviewer = new Pdfviewer();
                pdfviewer.setHflex("1");
                pdfviewer.setVflex("1");
                if (ext.startsWith("pdf"))
                    pdfviewer.setSrc("/servlets/download?id=" + URLEncoder.encode(file, "utf-8"));
                else if (ext.startsWith("doc")) {
                } else if (ext.startsWith("xls")) {
                    byte[] data = WebUtils.getFileContent(file);
                    ByteArrayInputStream bis = null;
                    ByteArrayOutputStream bos = null;
                    try {
                        bis = new ByteArrayInputStream(data);
                        bos = new ByteArrayOutputStream();
                        Importer importer = Importers.getImporter();
                        Book book = importer.imports(bis, "");
                        bos = new ByteArrayOutputStream();
                        Exporter exporter = Exporters.getExporter("pdf");
                        exporter.export(book, bos);
                        bos.flush();
                        AMedia media = new AMedia(name, "pdf", "application/pdf", bos.toByteArray());
                        pdfviewer.setContent(media);
                    } catch (IOException e) {
                    } finally {
                        IOUtils.closeQuietly(bis);
                        IOUtils.closeQuietly(bos);
                    }
                }
                pdfviewer.setParent(win);
            } else if (ext.equalsIgnoreCase("bmp")
                    || ext.equalsIgnoreCase("png")
                    || ext.equalsIgnoreCase("gif")
                    || ext.equalsIgnoreCase("jpg")
                    || ext.equalsIgnoreCase("pic")
                    || ext.equalsIgnoreCase("tif")) {
                Image image = new Image();
                image.setHflex("1");
                image.setVflex("1");
                image.setSrc("/servlets/download?id=" + URLEncoder.encode(file, "utf-8"));
                image.setParent(win);
            } else if (ext.equalsIgnoreCase("3gp")
                    || ext.equalsIgnoreCase("asf")
                    || ext.equalsIgnoreCase("avi")
                    || ext.equalsIgnoreCase("m4u")
                    || ext.equalsIgnoreCase("m4v")
                    || ext.equalsIgnoreCase("mov")
                    || ext.equalsIgnoreCase("mp4")
                    || ext.equalsIgnoreCase("mpg4")
                    || ext.equalsIgnoreCase("mpe")
                    || ext.equalsIgnoreCase("mpeg")
                    || ext.equalsIgnoreCase("mpg")) {
                Video video = new Video();
                video.setHflex("1");
                video.setVflex("1");
                video.setSrc("/servlets/download?id=" + URLEncoder.encode(file, "utf-8"));
                video.setParent(win);
                video.setAutoplay(true);
                video.setControls(true);
                video.setPlaying(true);
                video.setParent(win);
            } else if (ext.equalsIgnoreCase("mp3")
                    || ext.equalsIgnoreCase("mpga")
                    || ext.equalsIgnoreCase("ogg")
                    || ext.equalsIgnoreCase("wav")
                    || ext.equalsIgnoreCase("wma")
                    || ext.equalsIgnoreCase("wmv")
                    || ext.equalsIgnoreCase("m3u")
                    || ext.equalsIgnoreCase("m4a")
                    || ext.equalsIgnoreCase("m4b")
                    || ext.equalsIgnoreCase("m4p")) {
                Audio audio = new Audio();
                audio.setHflex("1");
                audio.setSrc("/servlets/download?id=" + URLEncoder.encode(file, "utf-8"));
                audio.setParent(win);
                audio.setAutoplay(true);
                audio.setControls(true);
                audio.setParent(win);
            }
            win.setPage(page);
            win.doHighlighted();
        } catch (UnsupportedEncodingException e) {
        }
    }

    public static boolean setBytesWithFile(byte[] bytes, String filePath) {
        InputStream in = new ByteArrayInputStream(bytes);
        boolean ret_bl = false;
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath, false);
            byte[] b = new byte[1024];
            int length = 0;
            while ((length = in.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.close();
            in.close();
            ret_bl = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret_bl;
    }

    public static boolean setStreamWithFile(String content, String filePath) {
        return FileUtil.setBytesWithFile(content.getBytes(), filePath);
    }

    public static Map<String, File> getAllFolderList(File file, Map<String, File> map, String rootPath) {

        if (Strings.isBlank(rootPath)) {
            rootPath = file.getName();
        }
        String path = file.getAbsolutePath();
        path = path.substring(path.indexOf(rootPath), path.length());
        map.put(path, file);
        if (file.isDirectory()) {
            File[] files = file.listFiles((root1, name) -> !name.startsWith("."));
            for (int i = 0; i < files.length; i++) {
                map = getAllFolderList(files[i], map, rootPath);
            }
        }
        return map;
    }

    public static boolean saveFolderByFile(File file, String parentPath) {

        Map<String, File> map = new LinkedHashMap<>();
        getAllFolderList(file, map, "");

        Iterator<Map.Entry<String, File>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, File> entry = iter.next();
            String key = entry.getKey();
            File value = entry.getValue();

            if (value.isDirectory()) {
                FileUtil.mkdirForNoExists(parentPath + File.separator + key);
            } else {
                boolean success = saveFileByFile(value, parentPath + File.separator + key);
                if (!success) {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean saveFileByFile(File file, String path) {
        InputStream is = null;
        OutputStream os = null;
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            byte[] b = new byte[1024];
            int length;
            os = new FileOutputStream(path);
            is = new FileInputStream(file);
            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        } finally {
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    //文件流复制文件
    public static void copyFileUsingFileChannels(File source, File dest) throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    public String getRootPath() {
        //从classpath根开始查找
        String path = this.getClass().getClassLoader().getResource("/").getPath();
        //String temp = path.replaceFirst("file:/", "").replaceFirst("WEB-INF/classes/", "");
        //文件分隔符（在 UNIX 系统中是“/”）
        String separator = System.getProperty("file.separator");
        if ("/".equals(separator)) {
            return path;
        } else {
            return path.substring(1);
        }
    }

    public static void copyDir(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);
        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }
        if (file.isDirectory()) {
            String[] filePath = file.list();
            for (int i = 0; i < filePath.length; i++) {
                if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
                    copyDir(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
                }

                if (new File(sourcePath + file.separator + filePath[i]).isFile()) {
                    copyFileUsingFileChannels(new File(sourcePath + file.separator + filePath[i]), new File(newPath + file.separator + filePath[i]));
                }

            }
        } else {
            copyFileUsingFileChannels(new File(sourcePath), new File(newPath + file.separator + file.getName()));
        }

    }

    public static void copyDirInFile(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);
        String[] filePath = file.list();

        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {
            if (new File(sourcePath + file.separator + filePath[i]).isFile()) {
                copyFileUsingFileChannels(new File(sourcePath + file.separator + filePath[i]), new File(newPath + file.separator + filePath[i]));
            }
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    public static void mkdirForNoExists(String dirPath) {
        if (!new File(dirPath).exists()) {
            try {
                FileUtils.forceMkdir(new File(dirPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断字符串中是否包含中文
     *
     * @param str 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 获得指定文件的byte数组
     *
     * @param filePath 路径
     * @return
     */
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * @功能 精确计算base64字符串文件大小（单位：B）
     * @注意 base64字符串(不含data : audio / wav ; base64, 文件头)
     */
    public static double base64fileSize(String base64String) {
        //1.获取base64字符串长度(不含data:audio/wav;base64,文件头)
        base64String = base64String.replaceAll("\n", "");
        int size0 = base64String.length();
        //2.获取字符串的尾巴的最后10个字符，用于判断尾巴是否有等号，正常生成的base64文件'等号'不会超过4个
        String tail = base64String.substring(size0 - 10);
        //3.找到等号，把等号也去掉,(等号其实是空的意思,不能算在文件大小里面)
        int equalIndex = tail.indexOf("=");
        if (equalIndex > 0) {
            size0 = size0 - (10 - equalIndex);
        }
        //4.计算后得到的文件流大小，单位为字节
        return size0 - ((double) size0 / 8) * 2;
    }

    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static Properties getJarMFWithFileName(String realFilePath) {
        try {
            JarFile jarFile = new JarFile(realFilePath);
            JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF");
            if (entry != null) {
                Properties prop = new Properties();
                prop.load(new InputStreamReader(jarFile.getInputStream(entry), "utf-8"));
                return prop;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InputStream getJarImageWithFileName(String realFilePath, String imageFilePath) {
        try {
            JarFile jarFile = new JarFile(realFilePath);
            JarEntry entry = jarFile.getJarEntry(imageFilePath);
            if (entry != null) {
                return jarFile.getInputStream(entry);
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void unJar(File src, File desDir) throws FileNotFoundException, IOException {
        JarInputStream jarIn = new JarInputStream(new BufferedInputStream(new FileInputStream(src)));
        byte[] bytes = new byte[1024];

        while (true) {
            ZipEntry entry = jarIn.getNextJarEntry();
            if (entry == null) break;

            File desTemp = desDir.getAbsoluteFile();

            if (entry.isDirectory()) {//jar条目是空目录
                if (!desTemp.exists()) desTemp.mkdirs();
                log.info("MakeDir: " + entry.getName());
            } else {//jar条目是文件
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(desTemp));
                int len = jarIn.read(bytes, 0, bytes.length);
                while (len != -1) {
                    out.write(bytes, 0, len);
                    len = jarIn.read(bytes, 0, bytes.length);
                }

                out.flush();
                out.close();
                log.info("Copyed: " + entry.getName());
            }
            jarIn.closeEntry();
        }
        //关闭JarInputStream
        jarIn.close();
    }

    public static List<String> getFilePathWithDirectory(String path) {
        List<String> files = new ArrayList<>();
        File file = new File(path);
        if (file.isDirectory() == false)
            return files;
        for (String filePath : file.list()) {
            if (new File(filePath).isDirectory() == false && filePath.equals(".DS_Store") == false && !filePath.equals("restore"))
                files.add(filePath);
        }
        return files;
    }

    public static String getStringWithStream(InputStream input) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = input.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

    public String getAllRole() {
        Pattern r = Pattern.compile(" value=\"([a-zA-z0-9_]*)\"");
        InputStream inputStream = getClass().getResourceAsStream("/web/include/editor/workbench/role.zul");
        String jsonResult = null;
        try {
            jsonResult = FileUtil.getStringWithStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error(jsonResult);
        if (jsonResult == null)
            return null;
        // 现在创建 matcher 对象
        Matcher m = r.matcher(jsonResult);
        HashMap<String, Integer> map = new HashMap<>();
        while (m.find()) {
            map.put(m.group(1), 1);
        }
        String s = JSON.toJSONString(map);
        log.info("s: " + s);
        return s;
    }

    public static void renameFile(File file, String name) {
        String oldPath = file.getAbsolutePath();
        if (!file.isDirectory()) {
            String suffix = oldPath.substring(oldPath.lastIndexOf("."), oldPath.length());
            oldPath = oldPath.substring(0, oldPath.lastIndexOf(file.getName()));
            file.renameTo(new File(oldPath + name + suffix));
        } else {
            file.renameTo(new File(oldPath + name));
        }
    }

    public static Long getFolderLength(File file, Long length) {
        if (file.isDirectory()) {
            File[] files = file.listFiles((root1, name) -> !name.startsWith("."));
            for (int i = 0; i < files.length; i++) {
                length = getFolderLength(files[i], length);
            }
        }
        length += file.length();
        return length;
    }

    /**
     * 解压
     *
     * @param srcFile
     * @param destDirPath
     * @throws RuntimeException
     */
    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 压缩文件
     *
     * @param src      压缩源
     * @param zipFile  压缩目的
     * @param fileRoot 文件夹为false，文件为true
     */
    public static void compress(File src, File zipFile, boolean fileRoot) {
        //
        if (!src.exists()) {
            throw new RuntimeException(src.getAbsolutePath() + "不存在");
        }
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(fos);
            String baseDir = "";
            compressbyType(src, zos, baseDir, fileRoot);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按照原路径的类型就行压缩。文件路径直接把文件压缩，
     *
     * @param src
     * @param zos
     * @param baseDir
     */
    private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean fileRoot) {

        if (!src.exists())
            return;
        //判断文件是否是文件，如果是文件调用compressFile方法,如果是路径，则调用compressDir方法；
        if (src.isFile()) {
            //src是文件，调用此方法
            compressFile(src, zos, baseDir, fileRoot);
        } else if (src.isDirectory()) {
            //src是文件夹，调用此方法
            compressDir(src, zos, baseDir, fileRoot);

        }

    }

    /**
     * 压缩文件
     */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir, boolean fileRoot) {
        if (!file.exists())
            return;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[1024];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
            bis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (fileRoot) {
            try {
                zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 压缩文件夹
     */
    private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean fileRoot) {
        if (!dir.exists())
            return;
        File[] files = dir.listFiles();
        if (files.length == 0) {
            try {
                zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for (File file : files) {
            compressbyType(file, zos, baseDir + dir.getName() + File.separator, fileRoot);
        }
        try {
            zos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
